package com.xingkeduo.configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service("redisMapCacheService")
public class RedisMapCacheService{
	private static final Logger log = LoggerFactory.getLogger(RedisMapCacheService.class);
	/**
	 * redis锁默认有效时间，永久
	 */
	public static long DEFULATE_LOCK_TIME = -1;
	
    @Autowired
    public StringRedisTemplate stringRedisTemplate;
    
    
	public void push(String key, String hashKey, String value) {
		stringRedisTemplate.opsForHash().put(key, hashKey, value);
	}
	public Boolean pushIfAbsent(String key, String hashKey, String value) {
		return pushIfAbsent(key, hashKey, value, null);
	}
	
	public Boolean pushIfAbsent(String key, String hashKey, String value,Long time) {
		log.info("【过期时间设置】key:{},hashKey:{},value:{},time:{}",key,hashKey,value,time);
		Boolean flag =Boolean.FALSE;
		if(time !=null) {
			flag = hasKey(key);
			log.info("【过期时间设置】是否存在key:{},boolean;{}",key,flag);
		}
		Boolean returnFlag = stringRedisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
		if(!flag && time != null) {
			setTime(key,time);
		}
		log.info("【过期时间设置】是否成功存储key:{},hashkey:{},boolean;{}",key,hashKey,returnFlag);
		return returnFlag;
	}
	
	public Object get(String key, String value) {
		return stringRedisTemplate.opsForHash().get(key, value);
	}
	
	public void delete(String key, String hashKeys) {
		stringRedisTemplate.opsForHash().delete(key, hashKeys);
	}
	
	public void setTime(String key, Long time) {
		stringRedisTemplate.expire(key,time , TimeUnit.MILLISECONDS);
	}
	
	public boolean hasKey(String key) {
		return stringRedisTemplate.hasKey(key);
	}
	
	public List<String> scan(String key,String pattern ,long count){
		ScanOptions _option = ScanOptions.scanOptions().count(count).match(pattern).build();
		Cursor<Map.Entry<Object, Object>> curosr = stringRedisTemplate.opsForHash().scan(key, _option);
		List<String> _result = new ArrayList<String>();
		int a = 0;
	    while(curosr.hasNext()){
	        Map.Entry<Object, Object> entry = curosr.next();
	        log.info(entry.getKey()+":"+entry.getValue());
	       _result.add(entry.getValue()+"");
	       a++;
	       if(count==a){
	    	   break;
	       }
	    }
	    log.info("总条数:"+a);
		return _result;
	}
	
	public HashOperations<String, Object, Object> getHashOperations() {
		HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
		return opsForHash;
	}
}
